package conf

import (
	"context"
	log "github.com/sirupsen/logrus"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var ctx = context.Background()
var PostDao *mongo.Client
var GroupDao *mongo.Client
var CommentDao *mongo.Client
var UserDaos []*mongo.Client

func InitDB() {
	if Env == PROD {
		PostDao = createDaoWithCredential("bizsrv", "nG6KNRwxVGz1jNdQ", "mongodb://db-comics-post-2-0-0.xiaoniangao.cn:27077")
		GroupDao = createDaoWithCredential("bizsrv", "tq0GGC5NkZGMXrT4", "mongodb://db-comics-group-2-0-0.xiaoniangao.cn:27077")
		CommentDao = createDaoWithCredential("bizsrv", "dPBdjR29QbZWHfeY", "mongodb://db-comics-comment-2-0-0.xiaoniangao.cn:27077")
		UserDaos = []*mongo.Client{
			createDaoWithCredential("bizsrv", "IPt1B9CxjcNOmNyU", "mongodb://db-comics-user-3-0-0.xiaoniangao.cn:27077"),
			createDaoWithCredential("bizsrv", "LrstSI9l6pDV6igQ", "mongodb://db-comics-user-4-0-0.xiaoniangao.cn:27077"),
		}
	} else {
		PostDao = createDao("mongodb://192.168.12.21:27017")
		GroupDao = createDao("mongodb://192.168.12.21:27017")
		CommentDao = createDao("mongodb://192.168.12.21:27017")
		UserDaos = []*mongo.Client{createDao("mongodb://192.168.12.21:27017"), createDao("mongodb://192.168.12.21:27017")}
	}

	ExitFunc = append(ExitFunc, exit)
}

func exit() {
	disconnect(PostDao)
	disconnect(GroupDao)
	disconnect(CommentDao)
	for _, v := range UserDaos {
		disconnect(v)
	}
}

func createDaoWithCredential(user, pass, url string) *mongo.Client {
	client, err := mongo.NewClient(options.Client().SetAuth(options.Credential{
		AuthMechanism: "SCRAM-SHA-1",
		AuthSource:    "admin",
		Username:      user,
		Password:      pass,
	}).ApplyURI(url))

	if err != nil {
		log.WithFields(log.Fields{"err": err, "url": url}).Error("链接数据库失败")
		return nil
	}
	err = client.Connect(ctx)
	if err != nil {
		log.WithFields(log.Fields{"err": err, "url": url}).Error("链接数据库失败")
		return nil
	}
	return client
}

func createDao(url string) *mongo.Client {
	client, err := mongo.NewClient(options.Client().ApplyURI(url))

	if err != nil {
		log.WithFields(log.Fields{"err": err, "url": url}).Error("链接数据库失败")
		return nil
	}
	err = client.Connect(ctx)
	if err != nil {
		log.WithFields(log.Fields{"err": err, "url": url}).Error("链接数据库失败")
		return nil
	}
	return client
}

func disconnect(client *mongo.Client) {
	err := client.Disconnect(ctx)
	if err != nil {
		log.WithFields(log.Fields{"err": err}).Error("断开数据库失败")
	} else {
		log.Info("断开数据库")
	}
}
